package org.otarriinae.security.base.service.impl;

import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.otarriinae.security.base.constant.StringsConstant;
import org.otarriinae.security.base.model.TokenUserDetails;
import org.otarriinae.security.base.service.TokenManager;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author xj
 * @since 1.0
 */
public class TokenManagerImpl implements TokenManager {



    /**
     * redis 过期时间
     */
    private Integer expiration;
    private RedisTemplate<String, String> valueOperations;

    public TokenManagerImpl(RedisTemplate<String, String> valueOperations,Integer expiration) {
        this.valueOperations = valueOperations;
        this.expiration =expiration;
    }


    /**
     *  获取token
     * @param tokenUserDetails 用户信息
     * @return token
     */
    @Override
    public String createToken(TokenUserDetails tokenUserDetails) {
        String token = UUID.randomUUID().toString();
        valueOperations.opsForValue().set(StringsConstant.getRedisToken(token), JSON.toJSONString(tokenUserDetails),expiration, TimeUnit.MINUTES);
        return token;
    }


    /**
     * 清除token
     *
     * @param token token
     *
     */
    @Override
    public void removeToken(String token) {
        if(StringUtils.isNotBlank(token)){
            valueOperations.delete(StringsConstant.getRedisToken(token));
        }
    }
}
